package com.landmesure.settings.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioGroup;

import com.code.EntityType;
import com.landmesure.bluetoothchat.R;
import com.landmesure.settings.SettingActivity;
import com.landmesure.settings.fragment.adpter.ListInfo;
import com.landmesure.settings.fragment.adpter.TypeListAdapter;
import com.landmesure.settings.fragment.argsinfo.ArgumentsInfo;
import com.landmesure.settings.fragment.argsinfo.DataHelper;
import com.landmesure.settings.fragment.tree.TypeTree;
import com.landmesure.settings.fragment.tree.TypeTreeNote;

import java.util.ArrayList;

public class TypeFragment extends Fragment {
    private static final String TAG = "TypeFragment";

    private Context mContext;
    private ArgumentsCallBack mCallBack;    //参数设置接口回调
    private ArrayList<TypeTreeNote> mTreeNotes;    //所有树节点集合
    private AdapterCallBack mAdapterCallBack;    //Adapter接口回调
    private TypeTree mTree;    //树对象
    private ArrayList<ListInfo> mListInfos = new ArrayList<>();    //列表信息集合，与Adapter交互
    private ArrayList<Integer> mListStatus = new ArrayList<>();    //记录列表中开关打开状态的id
    private DataHelper mDataHelper;    //DataHelper对象

    private RadioGroup mRadioGroup;
    private Button mQueryBtn;
    private Button mResetBtn;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        Log.i(TAG, "onCreate");
        super.onCreate(savedInstanceState);

        init();
    }

    /**
     * 获取ArgumentsFragment的实例
     */
    private void init() {
        mContext = getActivity();
        mCallBack = ((SettingActivity) mContext).getArgsFragInstance();
        if (null == mCallBack) {
            Log.e(TAG, "mCallBack is null");
            return;
        }

        mDataHelper = new DataHelper();
        mCallBack.setDataHelperInstance(mDataHelper);

        mTree = mDataHelper.getTree();
        setArguments();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             Bundle savedInstanceState) {
        final TypeListAdapter listAdapter = new TypeListAdapter(inflater, mListInfos);
        mAdapterCallBack = listAdapter;

        View view = inflater.inflate(R.layout.layout_type_fragment,
                container, false);
        ListView listView = view.findViewById(R.id.type_list);
        listView.setAdapter(listAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (!((SettingActivity) mContext).getIsArgsFragment()) {
                    return;
                }
                TypeTreeNote note = mTreeNotes.get(position);

                //查询参数按钮
                final int selection = mTree.getAllNotes().indexOf(note);
                setBtnStatus(mDataHelper.getEntityTypes(), mQueryBtn,
                        10, 2, selection);

                //复位参数
                if (0 == position) {
                    mResetBtn.setEnabled(true);
                } else {
                    mResetBtn.setEnabled(false);
                }

                mCallBack.setSelectNote(note, selection);
                displayArgs(note);

                int index = note.getId();
                if (mListStatus.contains(index)) {
                    closeChild(note);
                } else {
                    if (null != note.getChildNotes()) {
                        mListStatus.add(index);
                    }
                    openChild(position, note);
                }

                setListInfo();
                mAdapterCallBack.updateList(position, mListInfos);
            }
        });
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (!mTreeNotes.isEmpty()) {
            mCallBack.setArgumentsInit(mTreeNotes.get(0).getArgumentsInfos());
            mCallBack.setSelectNote(mTreeNotes.get(0), 0);
        }

        //查询功能按钮
        mQueryBtn = ((SettingActivity) mContext).findViewById(R.id.query_args);
        setBtnStatus(mDataHelper.getEntityTypes(), mQueryBtn, 10, 2, 0);

        //复位按钮
        mResetBtn = ((SettingActivity) mContext).findViewById(R.id.reset_args);

        //选项卡组
        mRadioGroup = ((Activity) mContext).findViewById(R.id.radiogroup_fragment);
        Log.i(TAG, "onActivityCreated");
    }

    /**
     * 设置按钮是否可以被操作
     */
    private void setBtnStatus(ArrayList<EntityType> entityTypes, Button button,
                              final int mcode, final int code, final int index) {
        if (entityTypes.isEmpty()) {
            Log.i(TAG, "entityTypes is empty");
            button.setEnabled(false);
            return;
        }
        if (mcode == entityTypes.get(index).getMcode() && code == entityTypes.get(index).getCode()) {
            button.setEnabled(true);
        } else {
            button.setEnabled(false);
        }
    }

    /**
     * 根据选项卡的不同，展示参数信息
     * @param note listView选中的节点
     */
    private void displayArgs(TypeTreeNote note) {
        switch (mRadioGroup.getCheckedRadioButtonId()) {
            case R.id.property_info:
                mCallBack.setArguments(note.getArgumentsInfos());
                break;
            case R.id.data_status:
                break;
            case R.id.result_info:
                break;
            default:
                break;
        }
    }

    /**
     * 根据所选板块获取并设置将要显示的参数值
     */
    @SuppressWarnings("unchecked")
    private void setArguments() {
        Log.i(TAG, "setArguments");
        mTreeNotes = mTree.getAllNotes();
        initNotes();
    }

    /**
     * 初始化树节点
     */
    private void initNotes() {
        ArrayList<TypeTreeNote> treeNotes = new ArrayList<>();
        for (TypeTreeNote note : mTreeNotes) {
            if (null != note.getParentNote()) {
                treeNotes.add(note);
            }
        }
        mTreeNotes.removeAll(treeNotes);
        setListInfo();
    }

    /**
     * 设置List信息
     */
    private void setListInfo() {
        mListInfos.clear();
        ListInfo info;
        for (TypeTreeNote note : mTreeNotes) {
            if (null != note.getChildNotes()) {
                info = new ListInfo(note.getName(), true, note.getLevel());
                mListInfos.add(info);
            } else {
                info = new ListInfo(note.getName(), false, note.getLevel());
                mListInfos.add(info);
            }
            if (mListStatus.contains(note.getId())) {
                info.setExpanded(true);
            }
        }
    }

    /**
     * 关闭子节点
     */
    private void closeChild(TypeTreeNote note) {
        ArrayList<TypeTreeNote> childNotes = note.getChildNotes();
        int index = note.getId();
        if (mListStatus.contains(index)) {
            mListStatus.remove(Integer.valueOf(index));
        }

        if (null != childNotes) {
            mTreeNotes.removeAll(childNotes);
            for (TypeTreeNote single : childNotes) {
                index = single.getId();
                if (mListStatus.contains(index)) {
                    mListStatus.remove(Integer.valueOf(index));
                }
                if (null != single.getChildNotes()) {
                    closeChild(single);
                }
            }
        }
    }

    /**
     * 展开子节点
     */
    private void openChild(int position, TypeTreeNote note) {
        ArrayList<TypeTreeNote> childNotes = note.getChildNotes();
        if (null != childNotes) {
            final int size = position + childNotes.size();
            for (int i = position + 1, index = 0; i <= size; i++, index++) {
                mTreeNotes.add(i, childNotes.get(index));
            }
        }
    }

    public interface AdapterCallBack {
        /**
         * 更新listView条目，实现展开或关闭
         * @param position 点击的条目
         */
        void updateList(int position, ArrayList<ListInfo> infos);
    }

    public interface ArgumentsCallBack {
        /**
         * 方法回调获取参数信息，实现实时刷新
         * @param infoArrayList 携带ArgumentsInfo信息的ArrayList
         */
        void setArguments(ArrayList<ArgumentsInfo> infoArrayList);

        /**
         * 方法回调获取参数信息，此方法仅在第一次初始化界面时调用
         * @param infoArrayList 携带ArgumentsInfo信息的ArrayList
         */
        void setArgumentsInit(ArrayList<ArgumentsInfo> infoArrayList);

        /**
         * 设置DataHelper实例
         * @param dataHelper 同一个DataHelper实例
         */
        void setDataHelperInstance(DataHelper dataHelper);

        /**
         * 设置所选对象的节点
         * @param note 对象节点
         * @param index 对象节点所在的位置（初始化后的集合）
         */
        void setSelectNote(TypeTreeNote note, int index);
    }
}
